const net = require('net');
// 创建一个 服务器
const server = net.createServer();
const fs = require('fs');
const path = require('path');

server.listen(9527); // 服务器监听9527端口

server.on('listening', () => {
  // 监听服务器是否启动
  console.log('server listen 9527');
});
// http://localhost:9527

server.on('connection', (socket) => {
  console.log('有客户端连接到服务器');
  // 每次 来一个请求 返回一个 socket 流
  socket.on('data', async (chunk) => {
    // 监听客户端发送的数据
    console.log(chunk.toString('utf-8'), '客户端传来的请求消息');
    const filename = path.resolve(__dirname, './hsq.jpg');
    const bodyBuffer = await fs.promises.readFile(filename);
    const headBuffer = Buffer.from(
      `HTTP/1.1 200 OK
Content-Type: image/jpeg

`,
      'utf-8'
    );
    const result = Buffer.concat([headBuffer, bodyBuffer]);
    socket.write(result);
    socket.end();
  });

  socket.on('end', () => {
    console.log('连接关闭了');
  });
});
